import React, { Component } from 'react';
import { connect } from 'dva';
import { message, Modal, Button } from 'antd';
import styles from './../Users.css';
import moment from 'moment';
import Factory from '../../factory';
import * as datetime from '../../../utils/datetime'
import dataEditCreate from '../../addons/DataEdit'
import dataTableCreate from '../../addons/DataTable'
import { deepEqual } from '../../../utils/objects';
import * as common from '../../../utils/common';
const daoName = "COMP_JC_MX";
const ButtonGroup = Button.Group;
const columns = [
  { title: '监测类型', width: 150, sorter: true, key: 'JCLX', dataIndex: 'JCLXCaption', filter: true, dispaly: true, export: true },
  { title: '客户名称', dataIndex: 'KHMC', key: 'KHMC', width: 250, sorter: true, dispaly: true, canEdit: true },
  { title: '账户', dataIndex: 'ACNO', key: 'ACNO', width: 300, sorter: true, dispaly: true, canEdit: true },
  { title: '金额（万元）', width: 150, sorter: false, className: "column-money", caption: 'JE', render: data => common.formatNumber(data.JE), key: 'JE', dispaly: true, filter: false },
  { title: '税前利率（%）', width: 120, sorter: false, className: "column-money", caption: 'LL', render: data => common.formatNumber(data.LL), key: 'LL', dispaly: true, filter: false },
  { title: '落实起始日', width: 120, sorter: true, key: 'LSKSR', caption: "LSKSR", render: data => datetime.format(data.LSKSR, "yyyy-MM-dd"), dispaly: true, filter: true },
  { title: '落实截止日', width: 120, sorter: true, key: 'LSJZR', caption: "LSJZR", render: data => datetime.format(data.LSJZR, "yyyy-MM-dd"), dispaly: true, filter: true },
];
let controls = [
  {
    name: "JCLX", label: "监测类型", required: true,
    data: [
      { value: '1', label: '一般贷款日均' },
      { value: '2', label: '贴现日均'},
      { value: '3', label: '福费廷日均'},
      { value: '4', label: '存款日均'},
      { value: '5', label: '存款利润'},
      { value: '6', label: '中收（含各类手续费收入）' },
    ],
    grid: 24 / 24, type: "select", layout: { labelSpan: 4, wrapperSpan: 19 }
  },
  { name: 'KHMC', required: true, type: 'text', label: '客户名称', grid: 24 / 24, layout: { labelSpan: 4, wrapperSpan: 19 } },
  {
    name: 'ACNO', required: false, type: 'textarea', label: '账户', grid: 24 / 24, layout: { labelSpan: 4, wrapperSpan: 19 }
    , placeholder: '请正确填写账号，多个账号请用英文的分号【;】进行分割。'
  },
  { name: 'JE', required: true, type: 'number', label: '金额(万)', grid: 24 / 24, dataType: "number", layout: { labelSpan: 4, wrapperSpan: 19 } },
  {
    name: 'LL', required: true, type: 'number', label: '税前利率(%)', grid: 24 / 24, dataType: "number",
    layout: { labelSpan: 4, wrapperSpan: 19 }, placeholder: '监测类型为存款利润、中收时，此处填入0。'
  },
  { name: "LSKSR", required: true, label: "落实起始日", dataType: "date", type: "date", grid: 12 / 24, layout: { labelSpan: 8, wrapperSpan: 15 } },
  { name: "LSJZR", required: true, label: "落实截止日", dataType: "date", type: "date", grid: 12 / 24, layout: { labelSpan: 8, wrapperSpan: 15 } },
];
const EditFrom = dataEditCreate(daoName);
const DataTable = dataTableCreate(daoName);
class SYJCLRSQ_MXForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataChange: false,
      rwid: 0,
      isShowBtn: true
    };
  }
  componentWillReceiveProps(nextProps) {
    if ((!deepEqual(nextProps.rwid, this.props.rwid)) || (!deepEqual(nextProps.isShowBtn, this.props.isShowBtn))) {
      this.loadData(nextProps.rwid)
      this.state.rwid = nextProps.rwid
      this.state.isShowBtn = nextProps.isShowBtn
    }
  }
  componentDidMount() {
    this.loadData(this.props.rwid)
  }
  loadData(rwid) {
    let seeks = [];
    let whereItems = [];
    whereItems.push({
      FieldName: "RWID",
      Operator: "=",
      FieldValues: '' + rwid
    })
    seeks.push({
      WhereItems: whereItems,
      RelationSign: "AND"
    })
    this.props.dispatch({
      type: `${daoName}/fetch`,
      payload: { daoName, page: 1, pageSize: 20, seeks }
    });
  }
  showModelHandler(isAdd) {
    let key = null
    if (!isAdd) {
      const len = this.props.selectedRowKeys.length;
      if (len === 0) {
        message.info('请选择要编辑的行，如果选择了多行，则使用最后一次选择！');
        return;
      }
      key = this.props.selectedRowKeys[len - 1]
    }
    this.props.dispatch({
      type: `${daoName}/openEdit`,
      payload: { key }
    });
  }
  deleteHandler() {
    const keys = this.props.selectedRowKeys;
    const len = keys.length;
    if (len === 0) {
      message.info('请选择要删除的行！');
      return;
    }
    Modal.confirm({
      title: '提示',
      content: `你确认要删除选中的${len}行数据吗？`,
      okText: '删除',
      cancelText: '取消',
      onOk: () => {
        this.props.dispatch({
          type: `${daoName}/remove`,
          payload: { daoName, keys },
        });
      }
    });
    this.props.dispatch({
      type: `${daoName}/reload`,
      payload: { daoName },
    });
  }
  edidOkHandler() {
    const form = this.refs.SYJCLRSQ_MXForm.getForm()
    form.validateFields((err, values) => {
      if (!err) {
        let t = `${daoName}/create`
        const { keyName, record } = this.props;
        let msg = "数据添加成功！"
        if (record[keyName]) {
          values[keyName] = record[keyName];
          t = `${daoName}/patch`
          msg = "数据修改成功！"
        }
        controls.map((c, i) => {
          if (c.type === 'cascader-select') {
            let vs = values[c.name];
            if (vs.length > 0) {
              values[c.name] = vs[vs.length - 1];
            } else {
              values[c.name] = null;
            }
          }
          if (c.dataType === "number") {
            values[c.name] = Number(values[c.name])
          } else if (c.dataType === "date" || c.dataType === "datetime") {
            values[c.name] = !values[c.name] ? null : new Date(values[c.name])
          } else {
            values[c.name] = values[c.name] === undefined ? null : values[c.name]
          }
          if (c.multiple || c.type === 'checkbox-group') {
            values[c.name] = values[c.name].join(',');
          }
        })
        this.state.dataChange = true;
        values.RWID = this.state.rwid
        this.props.dispatch({
          type: t,
          payload: { daoName, values },
        })
      }
    });
  };
  hideEditHandler() {
    const form = this.refs.SYJCLRSQ_MXForm.getForm();
    form.resetFields();
    if (this.state.dataChange) {
      this.props.dispatch({
        type: `${daoName}/reload`,
        payload: { daoName },
      });
      this.state.dataChange = false;
    }
    this.props.dispatch({
      type: `${daoName}/hideEdit`
    });
  };
  render() {
    let { showEdit, record, permID, popedomTypes, list } = this.props
    const pTypes = popedomTypes[permID]
    let data = null
    if (this.state.isShowBtn) {
      data = <ButtonGroup style={{ zIndex: 0 }}>
        <Button onClick={this.showModelHandler.bind(this, true)}>新增</Button>
        <Button onClick={this.showModelHandler.bind(this, false)}>修改</Button>
        <Button onClick={this.deleteHandler.bind(this)}>删除</Button>
      </ButtonGroup>
    }
    const zhcbl = list.length === 0 ? 0 : list[0].ZHCBL
    
    return (
      <div className={styles.normal} style={{ background: '#fff', marginTop: -16, padding: '5px 5px' }}>
        <div>
          <div className={styles.create}>
            {data}
          </div>
          <Modal title={
            <div>
              <div style={{ color: "red" }}>
                注：开票、开证、福费廷等手续费收入，监测类型请选择【中收】类型。
              </div>
            </div>
          } width={700} visible={showEdit} onOk={this.edidOkHandler.bind(this)} onCancel={this.hideEditHandler.bind(this)}
            footer={[
              <Button key="close" type="ghost" onClick={this.hideEditHandler.bind(this)}>关闭</Button>,
              <Button key="submit" type="primary" onClick={this.edidOkHandler.bind(this)}>保存</Button>
            ]}
          >

            <EditFrom ref="SYJCLRSQ_MXForm" daoName={daoName} controls={controls} record={record} />
          </Modal>
          <div>
            计算公式：<br />
            客户综合成本率=（一般贷款利率 * 一般贷款日均 * 一般贷款期限 + 贴现利率 * 贴现日均 * 贴现期限 + 福费廷利率 * 福费廷日均 * 福费廷期限 + 中收 - 存款日均 * 存款利率 * 存款期限）/（一般贷款日均 * 一般贷款期限 + 贴现日均 * 贴现期限 + 福费廷日均 * 福费廷期限）<br />
            <br />
            <div style={{ fontWeight: "bold" }}> 客户综合成本率：{zhcbl} %</div>
          </div>
          <DataTable ref="RoleTable" daoName={daoName} columns={columns} controls={controls} permID={permID} />
        </div>
      </div >
    )
  }
}
function mapStateToProps(state) {
  const { showEdit, record, selectedRowKeys, keyName, list } = state[daoName];
  const { userID, orgID, pOrgID, popedomTypes } = state.menus;
  return {
    userID,
    orgID,
    pOrgID,
    popedomTypes,
    showEdit,
    selectedRowKeys,
    keyName,
    record, list
  }
}
SYJCLRSQ_MXForm = connect(mapStateToProps)(SYJCLRSQ_MXForm)
export default SYJCLRSQ_MXForm;

let render = (props) => React.createElement(SYJCLRSQ_MXForm, props);
let f = new Factory()
f.set("SYJCLRSQ_MXForm", render)
